package com.example.myinventory.ui.item

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myinventory.R
import com.example.myinventory.data.ItemRepository
import com.example.myinventory.ui.navigation.NavigationDestination
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

object ItemEditDestination : NavigationDestination {
    override val route: String = "item_edit"
    override val titleRes: Int = R.string.item_edit_title
    const val itemIdArg = "itemId"
    val routeWithArgs = "$route/{$itemIdArg}"
}

class ItemEditViewModel(
    savedStateHandle: SavedStateHandle,
    private val itemRepository: ItemRepository
) : ViewModel() {
    private val itemId: Int = checkNotNull(savedStateHandle[ItemEditDestination.itemIdArg])
    var itemUiState by mutableStateOf(ItemUiState())
        private set

    init {
        viewModelScope.launch {
            itemUiState =
                itemRepository.getItemStream(itemId)
                    .filterNotNull()
                    .first()
                    .toItemUiState(true)
        }
    }

    suspend fun saveItem() {
        if (validateInput()) {
            itemRepository.updateItem(itemUiState.itemDetails.toItem())
        }
    }

    private fun validateInput(itemDetails: ItemDetails = itemUiState.itemDetails): Boolean {
        return with(itemDetails) {
            name.isNotBlank() && price.isNotBlank() && quantity.isNotBlank()
        }
    }

    fun updateUiState(itemDetails: ItemDetails) {
        itemUiState = ItemUiState(itemDetails = itemDetails, isEntryValid = validateInput(itemDetails))
    }
}
